package cn.maihe.elg.operation.web.business;

import cn.maihe.elg.operation.exception.ErrorCode;
import cn.maihe.elg.operation.exception.SystemRuntimeException;
import cn.maihe.elg.operation.model.bo.ApplyTemplatePdfParams;
import cn.maihe.elg.operation.model.dto.BaseResponse;
import cn.maihe.elg.operation.model.enums.AttachmentFileType;
import cn.maihe.elg.operation.model.enums.BidCustomerStatus;
import cn.maihe.elg.operation.model.enums.BidderLevel;
import cn.maihe.elg.operation.model.enums.CenterNoEnum;
import cn.maihe.elg.operation.model.enums.CustomerAttachmentTypeEnum;
import cn.maihe.elg.operation.model.enums.UserType;
import cn.maihe.elg.operation.model.vo.business.BidCustomerAuthQueryVO;
import cn.maihe.elg.operation.model.vo.business.BidCustomerAuthVO;
import cn.maihe.elg.operation.model.vo.business.BidCustomerBO;
import cn.maihe.elg.operation.model.vo.business.BidCustomerReportQueryVO;
import cn.maihe.elg.operation.model.vo.business.BidCustomerReportVO;
import cn.maihe.elg.operation.model.vo.business.BidCustomerSelfBO;
import cn.maihe.elg.operation.model.vo.business.ListBidCustomerVO;
import cn.maihe.elg.operation.repository.entity.*;
import cn.maihe.elg.operation.security.model.UserContext;
import cn.maihe.elg.operation.service.business.BidCustomerService;
import cn.maihe.elg.operation.service.business.CustomerAttachmentService;
import cn.maihe.elg.operation.service.business.ExchangeCenterService;
import cn.maihe.elg.operation.service.order.AcceptOrderInfoService;
import cn.maihe.elg.operation.service.order.GuaranteeAttachmentInfoService;
import cn.maihe.elg.operation.supports.electronicseal.anne.AnneSignService;
import cn.maihe.elg.operation.supports.system.ElgResourceService;
import cn.maihe.elg.operation.utils.CreateGuaranteeUtil;
import cn.maihe.elg.operation.utils.DateUtil;
import cn.maihe.elg.operation.utils.DownloadExcelTool;
import cn.maihe.elg.operation.utils.IdGenerate;
import cn.maihe.elg.operation.utils.UserContextUtil;
import cn.maihe.framework.starter.base.sql.PageBo;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Triple;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @Description 投标客户信息controller
 * @Author WJH
 * @Date 2021/03/25
 */
@Api(value = "投标客户信息管理", tags = "投标客户信息管理")
@RestController
@RequestMapping("/api")
@Slf4j
public class BidCustomerController {
    @Resource
    private BidCustomerService bidCustomerService;
    @Resource
    private CustomerAttachmentService customerAttachmentService;
    @Autowired
    private DownloadExcelTool downloadExcelTool;
    @Resource
    private AnneSignService anneSignService;
    @Resource
    private AcceptOrderInfoService acceptOrderInfoService;
    @Resource
    private GuaranteeAttachmentInfoService guaranteeAttachmentInfoService;
    @Resource
    private ElgResourceService elgResourceService;
    @Resource
    private ExchangeCenterService exchangeCenterService;

    @Value("${cn.maihe.elg.auto-audit-flag:false}")
    private Boolean autoAuditFlag;



    @ApiOperation(value = "分页查询投标客户信息", notes = "根据投标客户名称、机构名称、是否自动审批、是否黑名单 分页查询")
    @RequestMapping(value = "/bidCustomers", method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNo", value = "页数", dataType = "int", paramType = "query", required = true),
            @ApiImplicitParam(name = "pageSize", value = "每页大小", dataType = "int", paramType = "query", required = true),
            @ApiImplicitParam(name = "status", value = "审核状态", dataType = "int", paramType = "query", allowableValues = "1,2,3,4"),
            @ApiImplicitParam(name = "enableAutoApprove", value = "是否自动审批(0=否 1=是)", dataType = "int", paramType = "query", allowableValues = "0,1"),
            @ApiImplicitParam(name = "blacklistFlag", value = "是否黑名单(0=否 1=是)", dataType = "int", paramType = "query", allowableValues = "0,1"),
    })
    public PageBo<ListBidCustomerVO> pageList(int pageNo, int pageSize, ListBidCustomerVO vo) {
        return bidCustomerService.selectPageBySql(pageNo, pageSize, vo);
    }

    @ApiOperation(value = "获取投标客户信息", notes = "根据投标客户信息id获取投标客户信息")
    @ApiImplicitParam(name = "id", value = "投标客户信息id", dataType = "long", paramType = "path", required = true)
    @RequestMapping(value = "/bidCustomer/{id}", method = RequestMethod.GET)
    public BidCustomerBO getBidCustomer(@PathVariable Long id) {
        BidCustomerDO bidCustomerDO = bidCustomerService.selectById(id);
        if (bidCustomerDO == null) {
            throw new SystemRuntimeException(ErrorCode.NOTEXISTS, "投标客户信息id");
        }
        return bidCustomerService.getBidCustomerBO(id, bidCustomerDO);
    }



    @ApiOperation(value = "根据受理订单号获取投标客户信息", notes = "根据受理订单号获取投标客户信息")
    @ApiImplicitParam(name = "acceptOrderNo", value = "订单号", dataType = "String", paramType = "path", required = true)
    @RequestMapping(value = "/getBidCustomerByAcceptOrderNo/{acceptOrderNo}", method = RequestMethod.GET)
    public BidCustomerBO getBidCustomerByAcceptOrderNo(@PathVariable String acceptOrderNo) {
        AcceptOrderInfoDO acceptOrderInfoDO = acceptOrderInfoService.getByAcceptOrderNo(acceptOrderNo);
        if (Objects.isNull(acceptOrderInfoDO)) {
            throw new SystemRuntimeException(ErrorCode.NOTEXISTS, "受理订单信息");
        }
        Long bidCustomerId = acceptOrderInfoDO.getBidCustomerId();
        BidCustomerDO bidCustomerDO = bidCustomerService.selectById(bidCustomerId);
        if (Objects.isNull(bidCustomerDO)) {
            throw new SystemRuntimeException(ErrorCode.NOTEXISTS, "投标客户信息id");
        }

        Boolean result = bidCustomerService.isCompleteCustomerInfo(acceptOrderInfoDO, bidCustomerDO);
        if (result){
            bidCustomerDO.setStatus(0);
        }

        return bidCustomerService.getBidCustomerBO(bidCustomerId, bidCustomerDO);
    }

    @ApiOperation(value = "新增投标客户信息", notes = "新增投标客户信息")
    @RequestMapping(value = "/bidCustomer", method = RequestMethod.POST)
    public void createBidCustomer(@Validated @RequestBody BidCustomerVo vo) {
        // 暂无手动创建用户，不创建 valid VO
        BidCustomerDO cDO = BidCustomerDO.of(vo);
        cDO.setId(IdGenerate.getId());
        bidCustomerService.checkBidderContractInfo(cDO);

        if (bidCustomerService.existsCreditCode(cDO.getBidderCreditCode(), cDO.getCenterId(), cDO.getOrgId(), null)) {
            throw new SystemRuntimeException(ErrorCode.EXISTS, "投标客户统一社会信用代码", vo.getBidderCreditCode());
        }

        bidCustomerService.insert(cDO);
    }


    @ApiOperation(value = "修改投标客户信息(自我维护)", notes = "根据投标客户信息id修改投标客户信息")
    @RequestMapping(value = "/bidCustomer/update", method = RequestMethod.PUT)
    @Transactional(rollbackFor = Exception.class)
    public void updateBidCustomer(@Validated @RequestBody BidCustomerSelfBO vo) {
        Assert.notNull(vo.getId(), "投标客户主键Id不能为空");
        UserContext uc = UserContextUtil.getUserContext();
        Assert.isTrue(vo.getId().equals(uc.getBidderId()), "非本单位不能修改");
        BidCustomerDO cDO = new BidCustomerDO();
        BeanUtils.copyProperties(vo, cDO);
        bidCustomerService.checkBidderContractInfo(cDO);
        cDO.setUserModified(UserContextUtil.getUserContext().getUsername());
        cDO.setGmtModified(new Date());

        /*
          根据客户id获取客户信息，判断审核状态status是否为1补全状态字段completeflag是否为0 修改补全状态字段为1
        */
        BidCustomerDO bidCustomerDO = bidCustomerService.selectById(vo.getId());
        if (bidCustomerService.isUpdateCompleteFlag(bidCustomerDO)){
            cDO.setCompleteFlag(1);
        }

        List<CustomerAttachmentDO> customerAttachmentDOS = customerAttachmentService.selectList(
                CustomerAttachmentDOCondition.builder().andBidderIdEq(vo.getId())
                        .andAttachTypeIn(CustomerAttachmentTypeEnum.TYPE_0.getType(), CustomerAttachmentTypeEnum.TYPE_1.getType(),
                                CustomerAttachmentTypeEnum.TYPE_2.getType(), CustomerAttachmentTypeEnum.TYPE_3.getType(),
                                CustomerAttachmentTypeEnum.TYPE_7.getType())
                        .build()
        );

        Set<CustomerAttachmentTypeEnum> customerAttachmentTypes = new HashSet<>(
                Arrays.asList(CustomerAttachmentTypeEnum.TYPE_0, CustomerAttachmentTypeEnum.TYPE_1,
                CustomerAttachmentTypeEnum.TYPE_2, CustomerAttachmentTypeEnum.TYPE_3,
                CustomerAttachmentTypeEnum.TYPE_7));

        customerAttachmentDOS.forEach(attach -> {
            CustomerAttachmentTypeEnum type = CustomerAttachmentTypeEnum.resolve(attach.getAttachType());
            switch (type) {
                case TYPE_0:
                    attach.setAttachPath(vo.getBusinessLicensePic());
                    attach.setAttachFileName(vo.getBusinessLicensePic());
                    customerAttachmentTypes.remove(CustomerAttachmentTypeEnum.TYPE_0);
                    break;
                case TYPE_1:
                    attach.setAttachPath(vo.getAccountOpenLicensePic());
                    attach.setAttachFileName(vo.getAccountOpenLicensePic());
                    customerAttachmentTypes.remove(CustomerAttachmentTypeEnum.TYPE_1);
                    break;
                case TYPE_2:
                    attach.setAttachPath(vo.getLegalIdcardPic());
                    attach.setAttachFileName(vo.getLegalIdcardPic());
                    customerAttachmentTypes.remove(CustomerAttachmentTypeEnum.TYPE_2);
                    break;
                case TYPE_3:
                    attach.setAttachPath(vo.getLegalIdcard1Pic());
                    attach.setAttachFileName(vo.getLegalIdcard1Pic());
                    customerAttachmentTypes.remove(CustomerAttachmentTypeEnum.TYPE_3);
                    break;
                case TYPE_7:
                    attach.setAttachPath(vo.getQualificationPic());
                    attach.setAttachFileName(vo.getQualificationPic());
                    customerAttachmentTypes.remove(CustomerAttachmentTypeEnum.TYPE_7);
                    break;
            }
        });

        List<CustomerAttachmentDO> createCustomerAttachmentDOs = new ArrayList<>();
        customerAttachmentTypes.forEach(type -> {
            switch (type) {
                case TYPE_0:
                    CustomerAttachmentDO businessLicenseAttach = setCustomerAttachment(
                            vo.getId(), CustomerAttachmentTypeEnum.TYPE_0.getType(), vo.getBusinessLicensePic());
                    createCustomerAttachmentDOs.add(businessLicenseAttach);
                    break;
                case TYPE_1:
                    CustomerAttachmentDO accountOpenLicenseAttach = setCustomerAttachment(
                            vo.getId(), CustomerAttachmentTypeEnum.TYPE_1.getType(), vo.getAccountOpenLicensePic());
                    createCustomerAttachmentDOs.add(accountOpenLicenseAttach);
                    break;
                case TYPE_2:
                    CustomerAttachmentDO legalIdcardAttach = setCustomerAttachment(
                            vo.getId(), CustomerAttachmentTypeEnum.TYPE_2.getType(), vo.getLegalIdcardPic());
                    createCustomerAttachmentDOs.add(legalIdcardAttach);
                    break;
                case TYPE_3:
                    CustomerAttachmentDO legalIdcard1Attach = setCustomerAttachment(
                            vo.getId(), CustomerAttachmentTypeEnum.TYPE_3.getType(), vo.getLegalIdcard1Pic());
                    createCustomerAttachmentDOs.add(legalIdcard1Attach);
                    break;
                case TYPE_7:
                    CustomerAttachmentDO qualificationAttach = setCustomerAttachment(
                            vo.getId(), CustomerAttachmentTypeEnum.TYPE_7.getType(), vo.getQualificationPic());
                    createCustomerAttachmentDOs.add(qualificationAttach);
                    break;
            }
        });
        log.info("bidderId:{};customerAttachmentDOS.size:{};customerAttachmentTypes:{};createCustomerAttachmentDOs.size:{}",cDO.getId(),customerAttachmentDOS.size(),customerAttachmentTypes,createCustomerAttachmentDOs.size());
        bidCustomerService.modify(cDO, customerAttachmentDOS,createCustomerAttachmentDOs);


    }

    @ApiOperation(value = "修改投标客户信息", notes = "根据投标客户信息id修改投标客户信息")
    @RequestMapping(value = "/bidCustomer", method = RequestMethod.PUT)
    public BaseResponse<Object> modifyBidCustomer(@Validated @RequestBody BidCustomerBO vo) {
        // 暂无手动创建用户，不创建 valid VO
        BidCustomerDO cDO = BidCustomerDO.of(vo);
        Assert.notNull(vo.getId(), "投标客户主键Id不能为空");
        bidCustomerService.checkBidderContractInfo(cDO);
        cDO.setUserModified(UserContextUtil.getUserContext().getUsername());
        cDO.setGmtModified(new Date());

        /*
          根据客户id获取客户信息，判断审核状态status是否为1补全状态字段completeflag是否为0 修改补全状态字段为1
        */
        BidCustomerDO bidCustomerDO = bidCustomerService.selectById(vo.getId());
        if (bidCustomerService.isUpdateCompleteFlag(bidCustomerDO)){
            cDO.setCompleteFlag(1);
        }

        List<CustomerAttachmentDO> customerAttachmentDOS = customerAttachmentService.selectList(
                CustomerAttachmentDOCondition.builder().andBidderIdEq(vo.getId()).build()
        );
        Set<CustomerAttachmentTypeEnum> set = CustomerAttachmentTypeEnum.getAll();
        customerAttachmentDOS.forEach(attach -> {
            CustomerAttachmentTypeEnum type = CustomerAttachmentTypeEnum.resolve(attach.getAttachType());
            switch (type) {
                case TYPE_0:
                    attach.setAttachPath(vo.getBusinessLicensePic());
                    attach.setAttachFileName(vo.getBusinessLicensePic());
                    set.remove(CustomerAttachmentTypeEnum.TYPE_0);
                    break;
                case TYPE_1:
                    attach.setAttachPath(vo.getAccountOpenLicensePic());
                    attach.setAttachFileName(vo.getAccountOpenLicensePic());
                    set.remove(CustomerAttachmentTypeEnum.TYPE_1);
                    break;
                case TYPE_2:
                    attach.setAttachPath(vo.getLegalIdcardPic());
                    attach.setAttachFileName(vo.getLegalIdcardPic());
                    set.remove(CustomerAttachmentTypeEnum.TYPE_2);
                    break;
                case TYPE_3:
                    attach.setAttachPath(vo.getLegalIdcard1Pic());
                    attach.setAttachFileName(vo.getLegalIdcard1Pic());
                    set.remove(CustomerAttachmentTypeEnum.TYPE_3);
                    break;
                case TYPE_4:
                    attach.setAttachPath(vo.getApplyPic());
                    attach.setAttachFileName(vo.getApplyPic());
                    set.remove(CustomerAttachmentTypeEnum.TYPE_4);
                    break;
                case TYPE_5:
                    attach.setAttachPath(vo.getContactPic());
                    attach.setAttachFileName(vo.getContactPic());
                    set.remove(CustomerAttachmentTypeEnum.TYPE_5);
                    break;
                case TYPE_6:
                    attach.setAttachPath(vo.getAuthPic());
                    attach.setAttachFileName(vo.getAuthPic());
                    set.remove(CustomerAttachmentTypeEnum.TYPE_6);
                    break;
                case TYPE_7:
                    attach.setAttachPath(vo.getQualificationPic());
                    attach.setAttachFileName(vo.getQualificationPic());
                    set.remove(CustomerAttachmentTypeEnum.TYPE_7);
                    break;
            }
        });
        List<CustomerAttachmentDO> customerAttachmentDOS1 = new ArrayList<>();
        set.forEach(type -> {
            switch (type) {
                case TYPE_0:
                    CustomerAttachmentDO businessLicenseAttach = setCustomerAttachment(
                            vo.getId(), CustomerAttachmentTypeEnum.TYPE_0.getType(), vo.getBusinessLicensePic());
                    customerAttachmentDOS1.add(businessLicenseAttach);
                    break;
                case TYPE_1:
                    CustomerAttachmentDO accountOpenLicenseAttach = setCustomerAttachment(
                            vo.getId(), CustomerAttachmentTypeEnum.TYPE_1.getType(), vo.getAccountOpenLicensePic());
                    customerAttachmentDOS1.add(accountOpenLicenseAttach);
                    break;
                case TYPE_2:
                    CustomerAttachmentDO legalIdcardAttach = setCustomerAttachment(
                            vo.getId(), CustomerAttachmentTypeEnum.TYPE_2.getType(), vo.getLegalIdcardPic());
                    customerAttachmentDOS1.add(legalIdcardAttach);
                    break;
                case TYPE_3:
                    CustomerAttachmentDO legalIdcard1Attach = setCustomerAttachment(
                            vo.getId(), CustomerAttachmentTypeEnum.TYPE_3.getType(), vo.getLegalIdcard1Pic());
                    customerAttachmentDOS1.add(legalIdcard1Attach);
                    break;
                case TYPE_4:
                    CustomerAttachmentDO ApplyAttach = setCustomerAttachment(
                            vo.getId(), CustomerAttachmentTypeEnum.TYPE_4.getType(), vo.getApplyPic());
                    customerAttachmentDOS1.add(ApplyAttach);
                    break;
                case TYPE_5:
                    CustomerAttachmentDO contactAttach = setCustomerAttachment(
                            vo.getId(), CustomerAttachmentTypeEnum.TYPE_5.getType(), vo.getContactPic());
                    customerAttachmentDOS1.add(contactAttach);
                    break;
                case TYPE_6:
                    CustomerAttachmentDO authAttach = setCustomerAttachment(
                            vo.getId(), CustomerAttachmentTypeEnum.TYPE_6.getType(), vo.getAuthPic());
                    customerAttachmentDOS1.add(authAttach);
                    break;
                case TYPE_7:
                    CustomerAttachmentDO qualificationAttach = setCustomerAttachment(
                            vo.getId(), CustomerAttachmentTypeEnum.TYPE_7.getType(), vo.getQualificationPic());
                    customerAttachmentDOS1.add(qualificationAttach);
                    break;
            }
        });

        bidCustomerService.update(cDO, customerAttachmentDOS, customerAttachmentDOS1);

        if (UserContextUtil.getUserContext().getUserType() != UserType.BIDDER.getType()) {
            BidderLevel bidderLevel = BidderLevel.resolve(cDO.getBidderLevel());
            //资质级别不为空则开始计算更新已入库未计算保费的订单
            if (bidderLevel != null) {
                //更新未审核通过之前且已提交订单未计算手续费订单
                acceptOrderInfoService.updateUnFeeAcceptOrderInfo(cDO);
            }

        }

        BidCustomerDO bidCustomer = bidCustomerService.selectById(vo.getId());
        if (UserContextUtil.getUserContext().getUserType() == UserType.BIDDER.getType()) {
            if (BidCustomerStatus.NORMAL.getStatus() != bidCustomer.getStatus()) {
                if (autoAuditFlag){
                    // 客户信息自动审核通过
                    bidCustomerService.customerSuccess(bidCustomer);
                }else{
                    String acceptOrderNo = vo.getAcceptOrderNo();
                    if(StringUtils.isNotBlank(acceptOrderNo)){
                        AcceptOrderInfoDO acceptOrderInfoDO = acceptOrderInfoService.getByAcceptOrderNo(acceptOrderNo);
                        if(Objects.nonNull(acceptOrderInfoDO)){
                            CenterNoEnum centerNoEnum = exchangeCenterService.getCenterNoEnumById(acceptOrderInfoDO.getCenterId());
                            if(CreateGuaranteeUtil.isSuiXing(centerNoEnum,acceptOrderInfoDO.getClientId())){
                                // 客户信息自动审核通过
                                bidCustomerService.customerSuccess(bidCustomer);
                            }
                        }
                    }
                }
            }
        }

        JSONObject data = new JSONObject();
        data.put("id",bidCustomer.getId());
        data.put("status",bidCustomer.getStatus());
        return BaseResponse.success(data);
    }

    private CustomerAttachmentDO setCustomerAttachment(Long bidderId, String attachType, String fileName) {
        CustomerAttachmentDO customerAttachmentDO = new CustomerAttachmentDO();
        customerAttachmentDO.setId(IdGenerate.getId());
        customerAttachmentDO.setBidderId(bidderId);
        customerAttachmentDO.setAttachType(attachType);
        customerAttachmentDO.setAttachPath(fileName);
        customerAttachmentDO.setAttachFileName(fileName);
        return customerAttachmentDO;
    }

    @ApiOperation(value = "删除投标客户信息", notes = "根据投标客户信息id删除投标客户信息")
    @ApiImplicitParam(name = "id", value = "投标客户信息id", dataType = "long", paramType = "path", required = true)
    @RequestMapping(value = "/bidCustomer/{id}", method = RequestMethod.DELETE)
    public void deleteBidCustomer(@PathVariable Long id) {
        if (bidCustomerService.existsBidCustomerLinkedAcceptOrder(id)) {
            throw new SystemRuntimeException(ErrorCode.NONDELETE, "投标客户信息已存在关联受理订单");
        }
        bidCustomerService.deleteById(id);
    }

    @ApiOperation(value = "设置自动审批&黑名单标识", notes = "根据投标客户信息id设置自动审批&黑名单标识")
    @ApiImplicitParam(name = "id", value = "投标客户信息id", dataType = "long", paramType = "path", required = true)
    @RequestMapping(value = "/bidCustomer/set", method = RequestMethod.PUT)
    public void setBidCustomer(@Validated @RequestBody BidCustomerVo vo) {
        if (vo != null && vo.getId() != null) {
            BidCustomerDO cDO = BidCustomerDO.builder().id(vo.getId()).enableAutoApprove(vo.getEnableAutoApprove())
                    .blacklistFlag(vo.getBlacklistFlag()).userModified(UserContextUtil.getUserContext().getUsername())
                    .gmtModified(new Date()).build();
            bidCustomerService.updateById(cDO);
        }

    }

    @ApiOperation(value = "客户活跃度统计查询", notes = "客户活跃度统计查询")
    @RequestMapping(value = "/bidCustomerReports", method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNo", value = "页数", dataType = "int", paramType = "query", required = true),
            @ApiImplicitParam(name = "pageSize", value = "每页大小", dataType = "int", paramType = "query", required = true),
            @ApiImplicitParam(name = "bidderName", value = "客户名称", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "gmtTimeRange", value = "起始时间", dataType = "String", paramType = "query"),
    })
    public PageBo<BidCustomerReportVO> pageReportList(int pageNo, int pageSize, String gmtTimeRange, BidCustomerVo vo) {
        UserContext uc = UserContextUtil.getUserContext();
        if (UserType.GENERAL.getType() != uc.getUserType()) {
            vo.setOrgId(uc.getOrgId());
        }
        return bidCustomerService.selectReportPageBySql(pageNo, pageSize, gmtTimeRange, vo);
    }


    @ApiOperation(value = "客户活跃度统计下载", notes = "客户活跃度统计下载")
    @RequestMapping(value = "/bidCustomerReport/download", method = RequestMethod.POST)
    public void download(@Validated @RequestBody BidCustomerReportQueryVO vo, HttpServletResponse response) throws UnsupportedEncodingException {
        String path = "bidCustomerReport.xlsx";
        String filename = "渠道推广统计";

        UserContext uc = UserContextUtil.getUserContext();
        if (UserType.GENERAL.getType() != uc.getUserType()) {
            vo.setOrgId(uc.getOrgId());
        }

        List<BidCustomerReportVO> lists = bidCustomerService.listBidCustomerReportDownload(vo);

        Map<String, String> map = new HashMap<>();
        map.put("gmtTime", vo.getGmtTimeRange().stream().collect(Collectors.joining(" ~ ")));

        downloadExcelTool.downloadByTemplateName(path, filename, response, lists, map);
    }


    @ApiOperation(value = "投标客户审核", notes = "投标客户审核")
    @RequestMapping(value = "/bidCustomer/audit", method = RequestMethod.POST)
    public void auditCustomer(@Validated @RequestBody BidCustomerAuthVO vo) {

        BidCustomerDO bidCustomerDO = bidCustomerService.selectById(vo.getId());

        if (bidCustomerDO == null) {
            throw new SystemRuntimeException(ErrorCode.NOTEXISTS, "投标客户信息");
        }
        bidCustomerDO.setAuditDesc(vo.getAuditDesc());
        BidderLevel bidderLevel = BidderLevel.resolve(vo.getBidderLevel());
        if (bidderLevel != null) {
            bidCustomerDO.setBidderLevel(vo.getBidderLevel());
        }

        if (vo.getAuditStatus().equals("1")) {
            bidCustomerDO.setStatus(BidCustomerStatus.NORMAL.getStatus());
            bidCustomerDO.setEnterpriseId(null);
            //资质级别不为空则开始计算更新已入库未计算保费的订单
            bidCustomerService.customerSuccess(bidCustomerDO);
            //资质级别不为空则开始计算更新已入库未计算保费的订单
            if (bidderLevel != null) {
                //更新未审核通过之前且已提交订单未计算手续费订单
                acceptOrderInfoService.updateUnFeeAcceptOrderInfo(bidCustomerDO);
            }
//            anneSignService.createEnterprise4BidCustomer(vo.getId(), vo.getAuditDesc(), vo.getLegalPersonTel());
        } else {
            bidCustomerDO.setStatus(BidCustomerStatus.AUDIT_FAIL.getStatus());
            bidCustomerService.updateById(bidCustomerDO);
        }

    }


    @ApiOperation(value = "投标客户审核查询", notes = "投标客户审核查询")
    @RequestMapping(value = "/bidCustomer/auditQuery", method = RequestMethod.POST)
    public BidCustomerDO auditQuery(@Validated @RequestBody BidCustomerAuthQueryVO vo) {
//        anneSignService.queryEnterprise4BidCustomer(vo.getId());
        BidCustomerDO bidCustomerDO = bidCustomerService.selectById(vo.getId());
        return bidCustomerDO;

    }

    @ApiOperation(value = "投标客户下载创建附件信息", notes = "投标客户下载创建附件信息")
    @RequestMapping(value = "/bidCustomer/buildAttachment", method = RequestMethod.POST)
    public GuaranteeAttachmentInfoDO buildAttachment(@Validated @RequestBody BidCustomerBO bo) {
        GuaranteeAttachmentInfoDO guaranteeAttachmentInfo = null;
        AcceptOrderInfoDO acceptOrderInfoDO = acceptOrderInfoService.getByAcceptOrderNo(bo.getAcceptOrderNo());
        if (acceptOrderInfoDO != null) {
            AttachmentFileType fileType = AttachmentFileType.resolve(bo.getAttachmentFileType());
            GuaranteeAttachmentInfoDO attachmentInfoDO = guaranteeAttachmentInfoService.getTypeAttachmentByAcceptOrderNo(bo.getAcceptOrderNo(), fileType);
            if (attachmentInfoDO != null) {
                guaranteeAttachmentInfo = attachmentInfoDO;
            } else {
                //FIXME 暂只支持下载无文件则自动创建未签章的申请模板
                guaranteeAttachmentInfo = makeAndSaveApplyFile(acceptOrderInfoDO);
            }
        }
        return guaranteeAttachmentInfo;

    }

    private GuaranteeAttachmentInfoDO makeAndSaveApplyFile(AcceptOrderInfoDO acceptOrderInfo) {
        ApplyTemplatePdfParams params = new ApplyTemplatePdfParams();
        params.setBidderName(acceptOrderInfo.getBidCustomerName());
        params.setProjectName(acceptOrderInfo.getProjectName());
        Triple<String, String, String> triple = DateUtil.parseLocalDate();
        params.setYear(triple.getLeft());
        params.setMonth(triple.getMiddle());
        params.setDay(triple.getRight());

        String acceptOrderNo = acceptOrderInfo.getAcceptOrderNo();
        Path docxPath = elgResourceService.buildApplyFileByTemplate(acceptOrderNo, params);

        guaranteeAttachmentInfoService.saveOrUpdateAttachmentInfo(acceptOrderInfo, docxPath, AttachmentFileType.TYPE_12, "申请书未签章");
        return guaranteeAttachmentInfoService.getTypeAttachmentByAcceptOrderNo(acceptOrderNo, AttachmentFileType.TYPE_12);
    }

}
